/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package starwarslife;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Yann
 */
public class GameThread extends Thread {

    private static final int STEP_DURATION = 500;
    SWLController ctrl;
    int[][] bs;
    boolean running = true;

    public GameThread(SWLController ctrl, int[][] bs) {
        this.ctrl = ctrl;
        this.bs = bs;
    }

    @Override
    public void run() {
        nap(STEP_DURATION);
        while (running) {
            stepForward();
            nap(STEP_DURATION);
        }
    }

    private void stepForward() {
        for (int i = 0; i < bs.length; i++) {
            for (int j = 0; j < bs[i].length; j++) {
                if (bs[i][j] > 0) {
                    bs[i][j] = 0;
                    bs[(i + (j + 1) / bs.length) % bs.length][(j + 1) % bs.length] = 1; //Parcours la grille dans le sens de la lecture -> fonctionne
                    sendBoardState();
                    return;
                }
            }
        }
    }

    private void sendBoardState() {
        ctrl.setBoardState(bs);

    }

    private void nap(int i) {
        try {
            sleep(i);
        } catch (InterruptedException ex) {
            Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void gracefullyStop() {
        running = false;
    }
}